package cn.lysj.framework.common.security.jwt;


import cn.hutool.core.util.StrUtil;
import cn.lysj.framework.common.utils.web.Resp;
import cn.lysj.framework.common.utils.web.ResponseUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Exrickx
 */
@Slf4j
@Component
public class AuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            ResponseUtil.out(response, new Resp(Resp.INNER_ERROR,"用户名或密码错误"));
        } else if (e instanceof DisabledException) {
            ResponseUtil.out(response, new Resp(Resp.INNER_ERROR,"该账户已被禁用"));
        } else {
            ResponseUtil.out(response, new Resp(Resp.INNER_ERROR,"登录失败"));
        }
    }

    /**
     * 判断用户登陆错误次数
     */
    public boolean recordLoginTime(String username){

        return true;
    }
}
